﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using Coding4Fun.Phone.Controls;

namespace DSA
{
    public partial class MainPage : PhoneApplicationPage
    {
        public class mainListEntry
        {
            string name;

            public string Name { get { return name; } set { name = value; } }
        }

        int lists = 0;
        bool loaded = false;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Load the lists from xml
            LoadFromIsolatedStorage();
            loaded = true;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            // SAVE TO XML OR SOMETHING
            SaveToIsolatedStorage();

            // Exit out of applicatio, not to last page (creates infinite loops)
            // Wow, this is the only way to exit the app; no App.Exit()....
            throw new System.Exception();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!loaded)
                LoadFromIsolatedStorage();
        }

        private void LoadFromIsolatedStorage()
        {
            try
            {
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("main_lists.xml", FileMode.Open))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(List<mainListEntry>));
                        List<mainListEntry> data = (List<mainListEntry>)serializer.Deserialize(stream);

                        foreach (mainListEntry item in data)
                        {
                            ShoppingListEntryItem entry = new ShoppingListEntryItem();
                            entry.ListName.Text = item.Name;
                            listBoxMain.Items.Add(entry);
                        }
                    }
                }
            }
            catch
            {
                //add some code here
            }
        }

        private void SaveToIsolatedStorage()
        {
            // Write to the Isolated Storage
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Indent = true;

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("main_lists.xml", FileMode.Create))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<mainListEntry>));
                    using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
                    {
                        List<mainListEntry> save_list = new List<mainListEntry>();
                        for (int i = 0; i < listBoxMain.Items.Count; i++)
                        {
                            ShoppingListEntryItem temp = (ShoppingListEntryItem)listBoxMain.Items[i];
                            mainListEntry a = new mainListEntry();
                            a.Name = temp.ListName.Text;
                            save_list.Add(a);
                        }
                        serializer.Serialize(xmlWriter, save_list);
                    }
                }
            }
        }

        private void textBlock1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SaveToIsolatedStorage();
            NavigationService.Navigate(new Uri("/Shopping List Menu/PivotMenu.xaml", UriKind.Relative));
        }

        private void listBoxMain_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (listBoxMain.SelectedIndex == -1)
                return;

            // Navigate to the new page
            SaveToIsolatedStorage();
            NavigationService.Navigate(new Uri("/Shopping List Menu/PivotMenu.xaml?list=" + listBoxMain.SelectedIndex, UriKind.Relative));

            // Reset selected index to -1 (no selection)
            listBoxMain.SelectedIndex = -1;
        }

        private void SettingsButtonClick(object sender, EventArgs e)
        {
            SaveToIsolatedStorage();
            listBoxMain.Items.Clear();
            loaded = false;
            NavigationService.Navigate(new Uri("/List Menu/MainSettingsPage.xaml", UriKind.Relative));
        }

        private void AddButtonClick(object sender, EventArgs e)
        {
            ShoppingListEntryItem item = new ShoppingListEntryItem();
            lists++;
            item.ListName.Text = "List " + lists;
            listBoxMain.Items.Add(item);
        }

    }
}